import React, { useRef, useState, useEffect } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../../services/api';
import { KnowledgeBase } from '../../types';

const KnowledgeBaseList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);

  // 当从创建/编辑页面返回时，自动刷新列表
  useEffect(() => {
    if (location.state?.refresh) {
      actionRef.current?.reload();
      // 清除 state，避免重复刷新
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location, navigate]);

  const fetchKnowledgeBases = async (params: any) => {
    try {
      const response = await api.get('/knowledge-bases/', {
        params: {
          skip: (params.current - 1) * params.pageSize,
          limit: params.pageSize,
        },
      });
      
      // 后端返回的是数组，不是分页对象
      const data = response.data;
      const knowledgeBases = Array.isArray(data) ? data : (data.items || []);
      const total = data.total !== undefined ? data.total : knowledgeBases.length;
      
      // 转换字段名称：后端返回 camelCase，前端期望 snake_case
      const transformedData = knowledgeBases.map((kb: any) => ({
        ...kb,
        kb_admins: kb.adminUserIds || kb.kb_admins || [],
        team_access: kb.teamAccessIds || kb.team_access || [],
        documents: kb.documents || [],
        created_at: kb.createdAt || kb.created_at,
        updated_at: kb.updatedAt || kb.updated_at,
      }));
      
      return {
        data: transformedData,
        success: true,
        total: total,
      };
    } catch (error: any) {
      message.error('Failed to fetch knowledge bases');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await api.delete(`/knowledge-bases/${id}`);
      message.success('Knowledge base deleted successfully');
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || 'Failed to delete knowledge base');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<KnowledgeBase>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      copyable: true,
    },
    {
      title: 'Description',
      dataIndex: 'description',
      search: false,
      ellipsis: true,
    },
    {
      title: 'Admins',
      dataIndex: 'kb_admins',
      search: false,
      render: (_, record) => record.kb_admins.length,
    },
    {
      title: 'Team Access',
      dataIndex: 'team_access',
      search: false,
      render: (_, record) => record.team_access.length,
    },
    {
      title: 'Documents',
      dataIndex: 'documents',
      search: false,
      render: (_, record) => record.documents.length,
    },
    {
      title: 'Created At',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: 'Action',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/knowledge-bases/edit/${record.id}`)}
        >
          Edit
        </Button>,
        <Popconfirm
          key="delete"
          title="Are you sure to delete this knowledge base?"
          onConfirm={() => handleDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            Delete
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<KnowledgeBase>
      columns={columns}
      actionRef={actionRef}
      request={fetchKnowledgeBases}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle="Knowledge Base Management"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/knowledge-bases/create')}
          type="primary"
        >
          Create Knowledge Base
        </Button>,
      ]}
    />
  );
};

export default KnowledgeBaseList;
